local component = component or require("component")
local gpu = component.gpu
local test_image = {
	x = 28,
	y = 18,
	palette = {{
		char = " ",
		foreground = 0x000000,
		background = 0x000000
	},
	{
		char = " ",
		foreground = 0x000000,
		background = 0xffffff
	}},
	image = {}
}

local function draw(image)
	local prev_buffer = gpu.getActiveBuffer()
	local buffer = gpu.allocateBuffer(image.x,image.y)
	gpu.setActiveBuffer(buffer)
	for k,v in pairs(image.image) do
		gpu.setForeground(image.palette[v].foreground)
		gpu.setBackground(image.palette[v].background)
		gpu.set(((k-1)%image.x)+1,((k-1)//image.x)+1,image.palette[v].char)
	end
	gpu.setActiveBuffer(prev_buffer)
	return buffer
end

local function ser(path,image)
	local file = io.open(path, "wb")
	file:write(string.char(image.x,image.y,#image.palette))
	for k,v in ipairs(image.palette) do
		file:write(string.char(#v.char))
		file:write(v.char)
		local r,g,b = v.foreground//256//256,v.foreground//256%256,v.foreground%256
		file:write(string.char(r,g,b))
		local r,g,b = v.background//256//256,v.background//256%256,v.background%256
		file:write(string.char(r,g,b))
	end
	for k,v in ipairs(image.image) do
		file:write(string.char(v))
	end
	file:close()
end

local function deser(path)
	local test = {}
	local file = io.open(path, "rb")
	local size = 0
	test.x, test.y, size = string.byte(file:read(3),1,3)
	test.palette = {}
	for i=1,size do
		test.palette[i] = {}
		local charSize = file:read(1)
		test.palette[i].char = file:read(charSize)
		local rf,gf,bf,rb,gb,bb = string.byte(file:read(6),1,6)
		test.palette[i].foreground = rf*256*256+gf*256+bf
		test.palette[i].background = rb*256*256+gb*256+bb
	end
	test.image = {}
	for i=1,test.x*test.y do
		test.image[i] = string.byte(file:read(1))
	end
	file:close()
	return test
end

return {
	test_image = test_image,
	draw = draw,
	ser = ser,
	deser = deser
}
